package com.zm.authority.interceptor.controller;

import java.util.Collection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zm.authority.identity.po.ZmUser;
import com.zm.authority.identity.service.IdentityService;
import com.zm.common.core.util.Constant;


/**
 * LoginInterceptor
 * @author DENG.ZHUO.HUI
 * @email 13751827792@163.com
 * @date 2017年2月10日
 * @version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Resource(name="identityService")
	private IdentityService identityService;
	
	@Resource(name="sessionDAO")
	private SessionDAO sessionDAO;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//System.out.println("-----------> LoginInterceptor <-----------");
		Subject subject = SecurityUtils.getSubject();
		ZmUser user  = (ZmUser) request.getSession().getAttribute(Constant.USER_IN_SESSION);
		if(user == null){
			String userName = (String) subject.getPrincipal();
			if(!StringUtils.isEmpty(userName)){
				user = identityService.getUserByUserName(userName);
				subject.getSession().setAttribute(Constant.USER_IN_SESSION, user);
			}
		}else {
			Collection<Session> activeSessions = sessionDAO.getActiveSessions();
			int count = 0;
			for (Session session : activeSessions) {
				if(session.getAttribute(Constant.USER_IN_SESSION) != null){
					count++;
				}
			}
			//System.out.println("当前登录人数："+count);
			subject.getSession().setAttribute(Constant.LOGIN_USER_COUNT, count);
		}
		if(user == null){
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return false;
		}
		return true;
	}

}
